package com.bainuo.doctor.common.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.bainuo.doctor.common.R;
import com.bainuo.doctor.common.util.ToastUtils;
import com.bainuo.doctor.common.widget.CustomRefreshLayout;
import com.bainuo.doctor.common.widget.CustomToolbar;
import com.bainuo.doctor.common.widget.LoadingDialog;
import com.blankj.utilcode.utils.LogUtils;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Description:基类activity
 * 使用CustomToolbar (id 默认为R.id.toolbar),ButterKnife,
 * Created by MonkeyShen on 2017/1/16.
 * Mail:shenminjie92@sina.com
 */

public abstract class BaseActivity extends AppCompatActivity implements BaseView, CustomToolbar.OnToolbarClickListener {

    /**
     * 加载框view
     */
    private LoadingDialog mLoadingDialog;

    public Context mContext;
//    @BindView(R.id.toolbar)
    CustomToolbar mToolbar;

    boolean eventBus;


    public static  void toActivity(Context context,Class cls){
        Intent intent = new Intent(context,cls);
        context.startActivity(intent);
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //避免过度绘制，统一背景白色
        BaseApplication.getInstance().saveActivity(this);
        getWindow().setBackgroundDrawableResource(R.color.white);
        mLoadingDialog = new LoadingDialog(this);
        mContext = this;

    }

    protected void addEventBus(){
        EventBus.getDefault().register(this);
        eventBus = true;
    }

    @Override
    public abstract void initView();

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        super.setContentView(layoutResID);
        init();
    }

    Unbinder unbinder;
    /**
     * 初始化toolbar
     */
    private void init() {
        mToolbar = (CustomToolbar) findViewById(R.id.toolbar);
        unbinder = ButterKnife.bind(this);
        if (mToolbar != null) {
            //设置toolbar基础，监听事件、按钮显示
            mToolbar.setListener(this);
            setSupportActionBar(mToolbar);
            mToolbar.isShowLeftIcon(true);
            mToolbar.setMainTitleLeftDrawable(R.mipmap.icon_fanhui);
        }
    }

    protected void onStartOnece(){

    }

    boolean inited = false;
    @Override
    protected void onStart() {
        super.onStart();
        if (inited == false){
            inited = true;
            onStartOnece();
        }
    }



    protected View rootView;

    /**
     * 加载带有rootview的视图
     *
     * @param layoutResID layoutResID
     */
    public void setContentViewWithRoot(@LayoutRes int layoutResID) {
        super.setContentView(R.layout.layout_header);
        View view = getLayoutInflater().inflate(layoutResID, null, false);
        ViewGroup viewGroup = (ViewGroup) findViewById(R.id.root_content_view);
        viewGroup.addView(view);
        rootView = viewGroup;
        init();
        initView();
    }

    /**
     * 获取toolbar
     *
     * @return toolbar
     */
    public CustomToolbar getToolbar() {
        return mToolbar;
    }

    public void hideToolbar() {
        getToolbar().setVisibility(View.GONE);
    }

    /**
     * 设置title
     *
     * @param res 字符串资源
     */
    public void setToolbarTitle(int res) {
        String title = getString(res);
        setToolbarTitle(title);
    }

    /**
     * 设置title
     *
     * @param title 文本
     */
    public void setToolbarTitle(String title) {
        mToolbar.setMainTitle(title);
    }


    @Override
    public void showLoading() {
        if (!mLoadingDialog.isShowing() && !isFinishing()) {
            mLoadingDialog.show();
        }
    }

    @Override
    public void showLoading(String text) {
        if (!mLoadingDialog.isShowing() && !isFinishing()) {
            mLoadingDialog.show(text);
        }
    }


    /**
     * dialog  点击其他地方不消失
     * @param isCance false
     */
    public void showLoading(boolean isCance){
        if (!mLoadingDialog.isShowing()) {
            mLoadingDialog.show();
            mLoadingDialog.setCanceledOnTouchOutside(isCance);
            mLoadingDialog.setCancelable(isCance);
        }
    }
    public boolean isLoading() {
        return mLoadingDialog != null && mLoadingDialog.isShowing();
    }

    @Override
    public void hideLoading() {
        if (mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void showToast(CharSequence text) {
        ToastUtils.showToast(text);
    }

    @Override
    protected void onDestroy() {

        if (eventBus){
            EventBus.getDefault().unregister(this);
        }
        if (unbinder != null)
            unbinder.unbind();

        BaseApplication.getInstance().removeActivity(this);
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
        super.onDestroy();
    }


    /***************
     * toolbar点击回调事件
     **************/
    @Override
    public void onLeftIconClickListener(View leftView) {
        //结束activity
        finish();
        LogUtils.e("tag", "左按钮点击事件");
    }

    @Override
    public void onRightIconClickListener(View rightView) {
        LogUtils.e("tag", "右按钮点击事件");
    }

    @Override
    public void onMainTitleClickListener(View titleView) {
        LogUtils.e("tag", "标题点击事件处理");
    }

    @Override
    public void onRightOtherClickListener(View view) {

    }

    //初始化IM
    private void initEaseIm() {

    }

    /**
     * 关闭下拉刷新
     *
     * @param refreshLayout
     */
    public void refreshComplete(CustomRefreshLayout refreshLayout) {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
    }


    private boolean cancelKeyboard;
    public void enableTouchCancelKeyboard(boolean state){
        cancelKeyboard = state;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (!cancelKeyboard)
            return super.dispatchTouchEvent(ev);

        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }

            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     * @param v
     * @param event
     * @return
     */
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
//            event.getX() > left && event.getX() < right &&
            if (event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(BaseActivity.class.getSimpleName()); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写。"SplashScreen"为页面名称，可自定义)
        MobclickAgent.onResume(this);          //统计时长
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(BaseActivity.class.getSimpleName()); // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息。"SplashScreen"为页面名称，可自定义
        MobclickAgent.onPause(this);
    }

    /**
     * 设置友盟统计点击事件
     * @param evnetId  事件iD
     */
    public void setUmengEvent(String evnetId){
        MobclickAgent.onEvent(mContext, evnetId);
    }
}
